import axios from 'axios'
import { Toast } from 'antd-mobile'
import store from '../store/index'
import { setInfo } from '../store/slice/userSlice'
import router from '../router/index'

const instance = axios.create({
  // 根路径，配置为代理服务器的地址
  baseURL: 'http://localhost:5173'
})

// 请求拦截器
instance.interceptors.request.use(
  function (config) {
    // 在全局为 axios 配置接口的代理前缀
    if (!config.url.startsWith('/api')) {
      config.url = '/api' + config.url
    }

    config.headers.Authorization = store.getState().user.info?.token
    // Do something before request is sent
    // TODO1: 挂载 token
    // TODO2：展示 Loading 提示
    Toast.show({
      icon: 'loading',
      content: '加载中…',
      duration: 0 // 永远在界面上展示 Loading 状态，除非手动关闭它
    })
    return config
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    // TODO：隐藏 Loading 提示
    Toast.clear()
    return response.data
  },
  function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    // TODO：隐藏 Loading 提示
    Toast.clear()

    // 全局处理请求失败时候的弹窗
    if (error?.response?.data) {
      Toast.show({
        content: error.response.data?.message
      })
    }

    if (error.status === 401) {
      // 处理 401 状态码
      // 1. 清空仓库中的用户信息
      store.dispatch(setInfo(null))
      // 2. 跳转到登录页面
      router.navigate('/login')
    }

    return Promise.reject(error)
  }
)

export default instance
